package cn.autumnorange.app.scheduletask.consumer;

import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableScheduling
public class CompleteScheduleConfig implements SchedulingConfigurer {
  //   引入api模块会报错
  @Autowired private RedissonClient redissonClient;
  //  @Autowired private CronService cronService;
  //  @Mapper
  //  public interface CronMapper {
  //    @Select("select cron from cron limit 1")
  //    String getCron();
  //  }
  //
  //  @Autowired
  //  @SuppressWarnings("all")
  //  CronMapper cronMapper;

  /** 执行定时任务. */
  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    //    taskRegistrar.addTriggerTask(
    //        // 1.添加任务内容(Runnable)
    //        () -> System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime()),
    //        // 2.设置执行周期(Trigger)
    //        triggerContext -> {
    //          // 2.1 从数据库获取执行周期
    //          String cron = "0/5 * * * * ?";
    //          // 2.2 合法性校验.
    //          if (StringUtils.isEmpty(cron)) {
    //            // Omitted Code ..
    //          }
    //          // 2.3 返回执行周期(Date)
    //          return new CronTrigger(cron).nextExecutionTime(triggerContext);
    //        });

    boolean isLock = false;
    Long tryLockTime = 10L;

    RLock lock = redissonClient.getLock("triggerTask");
    try {
      isLock = lock.tryLock(tryLockTime, 10000, TimeUnit.MILLISECONDS);
      if (isLock) {

        Trigger trigger =
            new Trigger() {
              @Override
              public Date nextExecutionTime(TriggerContext triggerContext) {
                // 2.1 从数据库获取执行周期
                //            ResponseEntity<ResultDto<CronDto>> resultDtoResponseEntity =
                //                cronService.getRolesByUserId(1);
                String cron = "0/5 * * * * ?";

                //            if (resultDtoResponseEntity.getBody().getStatus() == 200) {
                //
                //              cron = resultDtoResponseEntity.getBody().getData().getCron();
                //            }

                // 2.2 合法性校验.
                if (StringUtils.isEmpty(cron)) {
                  // Omitted Code ..
                }
                // 2.3 返回执行周期(Date)
                return new CronTrigger(cron).nextExecutionTime(triggerContext);
              }
            };
        taskRegistrar.addTriggerTask(
            new Runnable() {
              @Override
              public void run() {
                System.out.println("执行定时任务: " + LocalDateTime.now().toLocalTime());
              }
            },
            trigger);
      } else {
        System.out.println("elselock失败");
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      if (isLock) {
        lock.unlock();
      } else {
        System.out.println("获取lock失败");
      }
    }
  }
}
